package com.anysdk.sms.demo.service;

import cn.com.anysdk.sms.api.ISmsService;
import cn.com.anysdk.sms.api.SmsRequest;
import cn.com.anysdk.sms.api.SmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Random;

@Service
public class LoginService {

    private final Map<String, String> codeStorage = new ConcurrentHashMap<>();
    private final Random random = new Random();

    @Autowired
    private ISmsService smsService;
    
    public String sendCode(String phone) {
        // 生成6位随机验证码
        String code = String.format("%06d", random.nextInt(1000000));
        
        // 构建短信请求
        SmsRequest request = SmsRequest.builder()
                .phoneNumber(phone)  // 使用传入的手机号
                .templateId("")
                .templateParams(Map.of("code", code))
                .signName("")
                .build();
        try {
            // 发送短信
            SmsResponse response = smsService.send(request);
            if (response.isSuccess()) {
                // 发送成功，保存验证码
                saveCode(phone, code);
                return code;
            } else {
                throw new RuntimeException("短信发送失败：" + response.getErrorMessage());
            }
        } catch (Exception e) {
            throw new RuntimeException("短信发送异常：" + e.getMessage());
        }
    }
    
    public void saveCode(String phone, String code) {
        codeStorage.put(phone, code);
    }
    
    public boolean verifyCode(String phone, String code) {
        String savedCode = codeStorage.get(phone);
        if (savedCode != null && savedCode.equals(code)) {
            // 验证成功后删除验证码
            codeStorage.remove(phone);
            return true;
        }
        return false;
    }
} 